﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using AutoMapper;

using Revis.VClinicNet.Core.Domain;
using Revis.VClinicNet.Core.Domain.Repository;
using Revis.VClinicNet.App.Internal.Dto;
using Revis.VClinicNet.App.Internal.Dto.Validation;
using Revis.VClinicNet.Core.Domain.Credentials;

namespace Revis.VClinicNet.App.Internal.ServiceImpl
{
    public class DoctorService : IDoctorService
    {
        private IDoctorRepository _doctorRepository = null;
        private IVisitRepository _visitRepository = null;
        private IWorkerUserRepository _workerUserRepository = null;

        public DoctorService(IDoctorRepository idr, IVisitRepository ivr, IWorkerUserRepository iwur)
        {
            _doctorRepository = idr;
            _visitRepository = ivr;
            _workerUserRepository = iwur;
        }

        public IList<DoctorInfoDto> ListAll()
        {
            IList<Doctor> doctors = _doctorRepository.FindAll();
            IList<DoctorInfoDto> listDto = Mapper.Map<IList<Doctor>, IList<DoctorInfoDto>>(doctors);
            return listDto;
        }

        public IList<DoctorInfoDto> ListAllActive()
        {
            IList<Doctor> doctors = _doctorRepository.FindAllActive();
            IList<DoctorInfoDto> listDto = Mapper.Map<IList<Doctor>, IList<DoctorInfoDto>>(doctors);
            return listDto;
        }

        public TDto Find<TDto>(long doctorId)
        {
            Doctor doctor = _doctorRepository.Find(doctorId);
            TDto dto = Mapper.Map<Doctor, TDto>(doctor);
            return dto;
        }

        public IList<VisitInfoDto> TodayVisits(long doctorId)
        {
            return VisitsForDateTime(doctorId, DateTime.Now);
        }

        private IList<VisitInfoDto> VisitsForDateTime(long doctorId, DateTime date)
        {
            IList<Visit> visits = _visitRepository.FindDoctorVisits(doctorId, date);
            visits = visits ?? new List<Visit>();
            IList<VisitInfoDto> visitsInfos = Mapper.Map<IList<Visit>, IList<VisitInfoDto>>(visits);
            return visitsInfos;
        }


        public DoctorWorkInfoDto FindWorkInfo(long doctorId, DateTime date)
        {
            Doctor doctor = _doctorRepository.Find(doctorId);
            if (doctor == null) {
                throw new ClinicException("Nie znaleziono takiego lekarza");
            }
            DoctorInfoDto doctorInfo = Mapper.Map<Doctor, DoctorInfoDto>(doctor);
            IList<VisitInfoDto> visits = VisitsForDateTime(doctorId, date);
            WorkTimeRoomInfoDto workTime = Mapper.Map<WorkTime, WorkTimeRoomInfoDto>(doctor.WorkSchedule.Get(date.DayOfWeek));
            return new DoctorWorkInfoDto() {
                Doctor = doctorInfo,
                Visits = visits,
                WorkTime = workTime
            };
        }

    }
}
